package com.terry.test1.newd;

import cn.hutool.core.util.PhoneUtil;
import lombok.Getter;

import javax.xml.bind.ValidationException;
import java.util.Arrays;

public class PhoneNumber {
    @Getter
    private final String number;

    public PhoneNumber(String number) throws ValidationException {
        if(number == null || PhoneUtil.isPhone(number)){
            throw new ValidationException("phone");
        }
        this.number = number;
    }

    public String getAreaCode(){
        //2.取电话里的区号
        for (int i = 0; i < number.length(); i++) {
            String prefix = number.substring(0, i);
            if (isAreaCode(prefix)) {
               return prefix;
            }
        }
        return null;
    }

    private static boolean isAreaCode(String prefix){
        String[] areas = new String[]{"0571", "021", "010"};
        return Arrays.asList(areas).contains(prefix);
    }
}
